package com.lyq;

import java.io.PrintWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class produceXML
{
	public void sendXML(PrintWriter pw, String[][] sourceStrings)
	{
		// 定义XML文档中文档节点和子节点
		Document questionDOC;
		Element questionList;
		Element question;
		Element questionNo;
		Element content;
		Element answerA;
		Element answerB;
		Element answerC;
		Element answerD;

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		
		try
		{
			DocumentBuilder db = dbf.newDocumentBuilder();

			questionDOC = db.newDocument();
			questionList = questionDOC.createElement("questionList");

			for (int i = 0; i < sourceStrings.length; i++)
			{
				// 生成各个节点
				question = questionDOC.createElement("question");
				questionNo = questionDOC.createElement("questionNo");
				content = questionDOC.createElement("content");
				answerA = questionDOC.createElement("answerA");
				answerB = questionDOC.createElement("answerB");
				answerC = questionDOC.createElement("answerC");
				answerD = questionDOC.createElement("answerD");
				
				// 给各节点的属性赋值
				questionNo.setAttribute("questionNo", sourceStrings[i][0]);
				content.setAttribute("content", sourceStrings[i][1]);
				answerA.setAttribute("answerA", sourceStrings[i][2]);
				answerB.setAttribute("answerB", sourceStrings[i][3]);
				answerC.setAttribute("answerC", sourceStrings[i][4]);
				answerD.setAttribute("answerD", sourceStrings[i][5]);

				// 将子节点加入父节点中
				question.appendChild(questionNo);
				question.appendChild(content);
				question.appendChild(answerA);
				question.appendChild(answerB);
				question.appendChild(answerC);
				question.appendChild(answerD);

				questionList.appendChild(question);
			}
			questionDOC.appendChild(questionList);

			TransformerFactory tf = TransformerFactory.newInstance();

			Transformer ts = tf.newTransformer();
			ts.transform(new DOMSource(questionDOC), new StreamResult(pw));

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
